package com.zzptc.easyshop.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

@WebServlet(name = "LoginCookieServlet")
public class LoginCookieServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String name = request.getParameter("name");
        String pwd = request.getParameter("pwd");
        HttpSession sess = request.getSession();
        if (request.getCookies() != null) {
            Cookie[] co = request.getCookies();
            for (Cookie c : co) {
                if (c.getName().equals("username")) {
                    sess.setAttribute("loginuame", c.getValue());
                }
                if (c.getName().equals("password")) {
                    sess.setAttribute("loginpwd", c.getValue());
                }
            }

        } else {
            //创建Cookie对象
            Cookie cookie = new Cookie("username", name);
            Cookie cookie1 = new Cookie("password", pwd);

            //设置生命周期
            cookie.setMaxAge(10 * 24 * 60 * 60);//保存十天
            cookie1.setMaxAge(10 * 24 * 60 * 60);

            //往客户端写
            response.addCookie(cookie);
            response.addCookie(cookie1);
        }
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}
